'''
    奔腾   benteng=xxx@xxxx
'''

import datetime
import json
import os
import pprint
import random
import time
import requests
import hashlib


def login(account, index):
    try:
        print(f'第{index}个账号 开始登录')
        url = f'https://yomi.fawcar.com.cn/btyomi/usercenter/app/v1/v2/baseLogin'
        param = {
            "password": "hKIdguH\/Q7Dz1RJ40Xls07UiCKkNgKhzcQH\/DIhTV5TLdv9uYRBJqocbpi7\/uthDPFhOBmdjZvBVKDi6WL9kI3lCMOLiUZ7biK0GVnm8cKG\/cvCr6x3X9ltxacS4l\/b0b1GW4i3oSxURXM50PtpfF1GfD9m8WOCpih2yBIG1uKY=",
            "account": account,
            "continueToLogIn": "0",
            "tspLoginRequest": {
                "brand": "apple",
                "model": "iPhone12,8",
                "deviceId": "8441429492857328"
            }
        }
        header = {
            'Host': 'yomi.fawcar.com.cn',
            'APP-Version': '4.1.0',
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'Connection': 'keep-alive',
            'Accept-Language': 'zh-Hans-CN;q=1',
            'Accept-Encoding': 'gzip, deflate, br'
        }
        response = requests.post(url=url, headers=header, data=json.dumps(param)).json()
        print(f'第{index}个账号 登录成功')
        return response
        # if response["status"] == "000000":
        #     return f'第{index}个账号 签到成功,返回：{response["data"]}\n'
        # return f'第{index}个账号 签到失败,返回：{response["data"]}\n'
    except Exception as e:
        return f'第{index}个账号 登录异常 {e}'


def get_nonce():
    """
        生成一个指定长度的随机字符串
        """
    randomlength = 16
    random_str = ''
    base_str = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    # print(random_str)
    return random_str


def genHeader(data):
    return {
        'Host': 'yomi.fawcar.com.cn',
        'APP-Version': '4.1.0',
        'User-Aid': f'{data["aid"]}',
        'User-Id': f'{data["userId"]}',
        'Device-Type': 'iPhone12,8',
        'Accept-Language': 'zh-Hans-CN;q=1',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept': '*/*',
        'User-Agent': 'BTYomi_iOS_dis/4.1.0 (iPhone; iOS 15.5; Scale/2.00)',
        'Connection': 'keep-alive',
        'V-Origin': 'APP',
        'Id-Token': f'{data["id_token"]}',
        'User-Code': f'{data["userCode"]}'
    }


def integral(data, header, index):
    try:
        print(f'第{index}个账号 开始获取积分')
        url = f'https://abjfapi.yuanchixinxi.com/api/sign/user'
        response = requests.post(url=url, headers=header, data=json.dumps({"sign": 1, "integral": 1, "all": 1})).json()
        result = response["data"]
        integral = result['integral']
        today_integral = result['today_integral']
        print(f'第{index}个账号 开始获取积分: 总积分[{integral}]，今日新增积分[{today_integral}]')
        return f'第{index}个账号 开始获取积分: 总积分[{integral}]，今日新增积分[{today_integral}]'
    except Exception as e:
        return f'第{index}个账号 签到异常 {e}'


def signIn(data, header, index):
    try:
        print(f'第{index}个账号 开始签到')
        url = f'https://abjfapi.yuanchixinxi.com/api/sign/integral'
        response = requests.post(url=url, headers=header, data=json.dumps({})).json()
        print(f'第{index}个账号 签到返回: {response}')
        if response["status"] == 200:
            return f'第{index}个账号 签到成功,返回：{response["msg"]}\n'
        return f'第{index}个账号 签到失败,返回：{response["msg"]}\n'
    except Exception as e:
        return f'第{index}个账号 签到异常 {e}'


'''
抽奖
'''


def lottery(data, header, index):
    try:
        print(f'第{index}个账号 开始抽奖')
        url = f'https://abjfapi.yuanchixinxi.com/api/v2/lottery'
        response = requests.post(url=url, headers=header, data=json.dumps({"id": 2, "type": "1"})).json()
        print(f'第{index}个账号 抽奖返回: {response}')
        if response["status"] == 200:
            return f'第{index}个账号 抽奖成功,返回：{response["data"]["prompt"]}\n'
        return f'第{index}个账号 抽奖失败,返回：{response["msg"]}\n'
    except Exception as e:
        return f'第{index}个账号 抽奖异常 {e}'


'''
阅读
'''


def getArticles(commentList, header, index):
    try:
        print(f'第{index}个账号 开始获取文章列表')
        url = f'https://yomi.fawcar.com.cn/btyomi/circle/app/v1/circle/getArticles?acttype=BTWTYPE&page=1&pageSize=10'
        response = requests.get(url=url, headers=header).json()
        msg = ""
        i = 1
        if response["code"] == '000000':
            for n, item in enumerate(response["data"]):
                comment = commentList[random.randint(0, len(commentList))]
                url = f'https://yomi.fawcar.com.cn/serverApi/circle/app/v1/circle/addComment'
                param = {"artcleid": f"{item['pkey']}", "commentUserId": "", "content": f"{comment}", "imgurl": ""}
                if (i > 5):
                    return msg
                portHeader = header
                portHeader['Content-Type'] = "application/json"
                response = requests.post(url=url, headers=portHeader, data=json.dumps(param)).json()
                if response["code"] == '000000':
                    print(f'第{index}个账号 评论成功,返回：{response}')
                    msg += f'第{index}个账号 评论成功,返回：{response}\n'
                else:
                    print(f'第{index}个账号 评论失败,返回：{response}')
                    msg += f'第{index}个账号 评论失败,返回：{response}\n'
                i += 1
                sleepmoment(30)
        msg += f'第{index}个账号 获取文章列表失败,返回：{response}\n'
        return msg
    except Exception as e:
        return f'第{index}个账号 获取文章列表异常 {e}'


'''
加入腾分圈
'''


def join(header, index):
    try:
        print(f'第{index}个账号 开始加入腾分圈')
        url = f'https://yomi.fawcar.com.cn/btyomi/circle/app/v1/circle/getMycircleByUserId'
        response = requests.get(url=url, headers=header).json()
        if response["code"] == '000000':
            print(f'第{index}个账号 评论成功')
            return f'第{index}个账号 评论成功,\n'
        else:
            print(f'第{index}个账号 评论失败,返回：{response}')
            return f'第{index}个账号 评论失败,返回：{response}\n'
        sleepmoment(30)
    except Exception as e:
        return f'第{index}个账号 分享异常 {e}'



'''
分享
'''


def share(header, index):
    try:
        print(f'第{index}个账号 开始分享')
        url = f'https://yomi.fawcar.com.cn/btyomi/member/app/v1/member/finishTask?changeDesc=%E8%BD%AC%E5%8F%91%E5%86%85%E5%AE%B9%E8%87%B3%E6%9C%8B%E5%8F%8B%E5%9C%88&money=&tacticsCode=PR-BT-Circle_friends_2&taskId=20'
        response = requests.get(url=url, headers=header).json()
        if response["code"] == '000000':
            print(f'第{index}个账号 分享成功')
            return f'第{index}个账号 分享成功,\n'
        else:
            print(f'第{index}个账号 分享失败,返回：{response}')
            return f'第{index}个账号 分享失败,返回：{response}\n'
        sleepmoment(30)
    except Exception as e:
        return f'第{index}个账号 分享异常 {e}'


'''
答题
'''


def question(data, header, index):
    try:
        print(f'第{index}个账号 开始答题')
        url = f'https://abjfapi.yuanchixinxi.com/api/question/list'
        response = requests.get(url=url, headers=header).json()
        data = response["data"]
        eid = data["e_id"]
        list = data["list"]
        answer_list = []
        for item in list:
            answer = {"question_id": item["id"], "answer": item["answer"]}
            answer_list.append(answer)
            sleepmoment(4)

        answer_data = {"e_id": eid, "list": answer_list}
        url = 'https://abjfapi.yuanchixinxi.com/api/question/submit'
        response = requests.post(url=url, headers=header, data=json.dumps(answer_data)).json()
        print(f'第{index}个账号 答题返回: {response}')
        if response["status"] == 200:
            return f'第{index}个账号 答题成功\n'
        return f'第{index}个账号 答题失败\n'
    except Exception as e:
        return f'第{index}个账号 答题异常 {e}'


def webhook(message, webhookToken):
    url = f'https://www.pushplus.plus/send'
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "token": webhookToken,
        "title": "一汽奔腾",
        "content": message,
        "template": "json"
    }
    response = requests.post(url=url, data=json.dumps(data), headers=headers).json()
    print(f"推送成功")


def genEnvs():
    cks = os.environ['benteng']
    cks = cks.split('@')
    tokenArr = []
    for ck in cks:
        tokenArr.append(ck)
    return tokenArr


def sleepmoment(num):
    random_seconds = random.randint(1, num)
    print(f'休眠{random_seconds}秒')
    time.sleep(random_seconds)


if __name__ == '__main__':
    print('开始执行...')
    sleepmoment(60)
    tokenArray = genEnvs()
    length = len(tokenArray)
    print(f'读取到{length}个账号')
    webhookToken = os.environ['PUSH_PLUS_TOKEN']
    msg = ""
    commentList = ["一汽奔腾，奔腾不息！", "萌宠驾到，福利加码！", "悦己奔腾，福利加码！", "奔腾小马，来自一汽！",
                   "生活不是赶路，是感受风！"]
    for index, ck in enumerate(tokenArray):
        loginRes = login(ck, index + 1)
        if loginRes["code"] != "000000":
            continue
        data = loginRes["data"]
        header = genHeader(data)
        msg += getArticles(commentList, header, index + 1)
        sleepmoment(30)
        msg += join(header, index + 1)
        sleepmoment(30)
        msg += share(header, index + 1)
        sleepmoment(30)
        # msg += signIn(ck,  header, index + 1)
        # sleepmoment(30)
        # msg += lottery(ck, header, index + 1)
        # sleepmoment(30)
        # msg += question(ck, header, index + 1)
        # sleepmoment(30)

        # msg += share(ck, header, index + 1)
        # sleepmoment(30)
        # msg += integral(ck,  header, index + 1)
        # sleepmoment(30)
    webhook(msg, webhookToken)
